package org.xfy.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.xfy.common.constant.OrderStatus;
import org.xfy.common.constant.RConst;
import org.xfy.common.result.JsonResult;
import org.xfy.common.util.AssertUtil;
import org.xfy.common.util.CodeGenerateUtils;
import org.xfy.ymcc.domain.CourseDoc;
import org.xfy.ymcc.domain.CourseOrder;
import org.xfy.ymcc.domain.CourseOrderItem;
import org.xfy.ymcc.domain.PayOrder;
import org.xfy.ymcc.dto.OrderDto;
import org.xfy.ymcc.feign.SearchFeignClient;
import org.xfy.ymcc.mapper.CourseOrderMapper;
import org.xfy.ymcc.producer.OrderProducer;
import org.xfy.ymcc.service.ICourseOrderItemService;
import org.xfy.ymcc.service.ICourseOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xfy
 * @since 2023-12-08
 */
@Service
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder> implements ICourseOrderService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private SearchFeignClient searchFeignClient;
    @Autowired
    private ICourseOrderItemService courseOrderItemService;
    @Autowired
    private OrderProducer orderProducer;

    @Override
    public JsonResult placeOrder(OrderDto orderDto, Long userId) {
        //幂等性校验
        Boolean b = redisTemplate.hasKey(orderDto.getCourseIds().get(0).toString());
        redisTemplate.delete(orderDto.getCourseIds().get(0).toString());
        AssertUtil.isTrue(b, "请勿重复提交");
        //拿到课程id
        List<Long> courseIds = orderDto.getCourseIds();
        //去查询es?
        JsonResult course = searchFeignClient.getCourse(courseIds);
        List<CourseDoc> courseDocList = JSONObject.parseArray(JSON.toJSONString(course.getData()), CourseDoc.class);
        //新增课程订单
        //去保存订单
        CourseOrder courseOrder = new CourseOrder();
        String orderNo = CodeGenerateUtils.generateOrderSn(userId);
        courseOrder.setCreateTime(new Date());
        courseOrder.setOrderNo(orderNo);
        super.saveOrUpdate(courseOrder);
        //保存明细
        List<CourseOrderItem> list = saveCourseOrderItem(courseDocList, courseOrder);
        courseOrder.setUserId(userId);
        courseOrder.setTitle("普通订单");
        courseOrder.setPayType(orderDto.getPayType());
        courseOrder.setOrderType(RConst.Num.INT_0);

        //构建支付订单信息
        PayOrder payOrder = new PayOrder();
        payOrder.setCreateTime(new Date());
        payOrder.setAmount(courseOrder.getPayAmount());
        payOrder.setPayType(courseOrder.getPayType());
        List<String> collect = courseIds.stream().map(id -> id.toString()).collect(Collectors.toList());
        payOrder.setRelationId(String.join(",",collect));
        payOrder.setOrderNo(orderNo);
        payOrder.setUserId(userId);
        payOrder.setSubject(courseOrder.getTitle());
        payOrder.setPayStatus(OrderStatus.ORDER_SUCCESS);
        Map<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("courseOrder",courseOrder);
        //发送事务消息
        orderProducer.sendTransaction(map,payOrder);

        //发送MQ消息通知用户下单成功
        /*Map<String,Object> map1 = new HashMap<>();
        map.put("userId",userId);
        map.put("content","该"+orderNo+"订单已下单成功，请尽快支付");
        orderProducer.notice(JSON.toJSONString(map1));*/

        //返回订单号  前端拿订单号跳转支付页面
        return JsonResult.success().setData(orderNo);
    }

    /**
     * 保存课程订单明细
     *
     * @param courseDocList
     */
    private List<CourseOrderItem>  saveCourseOrderItem(List<CourseDoc> courseDocList, CourseOrder courseOrder) {
        //保存订单明细
        List<CourseOrderItem> list = new ArrayList<>();
        //支付金额
        Double payAmount = new Double(0);
        //总金额
        Double countAmount = new Double(0);
        for (CourseDoc courseDoc : courseDocList) {
            CourseOrderItem courseOrderItem = new CourseOrderItem();
            courseOrderItem.setOrderId(courseOrder.getId());//？
            courseOrderItem.setOrderNo(courseOrder.getOrderNo());//
            courseOrderItem.setAmount(new BigDecimal(courseDoc.getPrice()));
            payAmount += courseDoc.getPrice();
            courseOrderItem.setPrice(new BigDecimal(courseDoc.getPriceOld()));
            countAmount += courseDoc.getPriceOld();
            courseOrderItem.setCount(RConst.Num.INT_1);
            courseOrderItem.setCourseId(courseDoc.getId());
            courseOrderItem.setCourseName(courseDoc.getName());
            courseOrderItem.setCoursePic(courseDoc.getPic());
            list.add(courseOrderItem);
        }

        courseOrder.setTotalAmount(new BigDecimal(countAmount));
        courseOrder.setPayAmount(new BigDecimal(payAmount));
        courseOrder.setDiscountAmount(new BigDecimal(countAmount - payAmount));
        courseOrder.setTotalCount(courseDocList.size());
        courseOrder.setStatusOrder(OrderStatus.ORDER_SUCCESS);
        return list;
    }

}
